import BlockButton from '@/components/BlockButton';
import Dialog from '@/components/Dialog';
import SelectRadios from '@/components/SelectRadios';
import TextButton from '@/components/TextButton';
import { AppContext } from '@/store/index.context';
import React, { useCallback, useContext, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { StartOneContext } from '../index.context';
import classes from './index.module.css';

export default function PersonSelect() {
  const { personStore, gameStore } = useContext(AppContext);
  const { showPersons, getPersonById } = personStore;
  const { setGamePerson } = gameStore;
  const [selectId, setSelectId] = useState('');
  const { setShowPersonSelect, position } = useContext(StartOneContext);
  const navigate = useNavigate();

  const personOptions = useMemo(
    function () {
      return showPersons.map(p => ({
        label: p.name,
        value: p.id,
        key: p.name,
      }));
    },
    [showPersons],
  );

  const handleConfirm = useCallback(
    function () {
      const person = getPersonById(selectId);
      if (person && position) {
        setShowPersonSelect(false);
        setGamePerson(position, person.id);
      } else {
        // 报错提示
      }
    },
    [getPersonById, selectId, setShowPersonSelect, position, setGamePerson],
  );

  const handleCancel = useCallback(
    function () {
      setShowPersonSelect(false);
    },
    [setShowPersonSelect],
  );

  return (
    <Dialog title="选择选手">
      <>
        <div className={classes.Operations}>
          <TextButton onClick={() => navigate('/athletes')}>添加选手</TextButton>
        </div>
        <SelectRadios
          options={personOptions}
          value={selectId}
          onChange={val => setSelectId(val)}></SelectRadios>
        <div className={classes.Footer}>
          <BlockButton text="取消" onClick={handleCancel} />
          <BlockButton text="确认" type="primary" onClick={handleConfirm} />
        </div>
      </>
    </Dialog>
  );
}
